#include "NameDB.h"
#include <stdexcept>
#include <fstream>
#include <iostream>

using namespace std;

NameDB::NameDB(string_view nameFile)
{
	ifstream inputFile(nameFile.data());
	if (!inputFile) {
		throw invalid_argument("Unable to open file");
	}

	string name;
	while (inputFile >> name) {
		++mNames[name];
	}
}

int NameDB::getNameRank(string_view name) const
{
	int num = getAbsoluteNumber(name);
	if (num == -1) {
		return -1;
	}

	int rank = 1;
	for (auto& entry : mNames) {
		if (entry.second > num) {
			rank++;
		}
	}

	return rank;
}

int NameDB::getAbsoluteNumber(string_view name) const
{
	auto res = mNames.find(name.data());
	if (res != end(mNames)) {
		return res->second;
	}

	return -1;
}
